//
//  StatusListViewModel.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/25.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class StatusListViewModel: NSObject {
    
    //模型数组
    lazy var statuses = [Status]()
    
    func loadHomeData(isPullUp: Bool, finished:(isSuccess: Bool) -> ()) {
        let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel.sharedAccountViewModel.token else {
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        
        var parameters = ["access_token": token]
        
        var since_id: Int64 = 0
        
        var max_id: Int64 = 0
        
        if isPullUp {
            max_id = self.statuses.last?.id ?? 0
        }else {
            since_id = self.statuses.first?.id ?? 0
        }
        
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        HTTPClient.sharedClient.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if  error != nil {
                finished(isSuccess: false)
                return
            }
            //2. 在字典中通过 "statuses"这个key 来去获取微博数组数据
            guard let array = dict!["statuses"] as? [[String : AnyObject]] else {
                finished(isSuccess: false)
                return
            }
            //实例化模型数据
            var tempArray = [Status]()
            
            //3.遍历数组 获取单个的字典对象
            for item in array {
                //4.字典转模型
                let s = Status(dict: item)
                tempArray.append(s)
            }
            
            //记录临时数组
            if since_id > 0 {
                //在数组的面前进行添加的操作的操作
                self.statuses = tempArray + self.statuses
                
            }else if max_id > 0 {
                //上拉加载更多数据 追加数组数据
                //移除第一条数据
                self.statuses += tempArray
            } else {
                //首次加载数据  下拉刷新
                self.statuses = tempArray
            }
            
            self.cacheStatusImage(tempArray, finished: finished)
            
        }

    }
    
    private func cacheStatusImage(array: [Status], finished: (isSuccess:Bool) -> ()){
        if array.count == 0 {
            finished(isSuccess: true)
            return
        }
        
        //群组队列 监听一组异步组任务完成得到统一回调
        //面临的问题 是多少次的异步任务执行  需要得到统一的完成回调
        //遍历模型数组
        let group = dispatch_group_create()
        for s in array {
            //判断模型中 imageURLs数量
            let imageCount = s.pictureURLs?.count ?? 0
            if imageCount == 1 {
                //完成单张图片下载
                //在将要开始异步任务前面 向群组中添加异步任务
                //dispatch_group_enter 和dispatch_group_leave 是成对出现的
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(s.pictureURLs![0], options: [], progress:nil , completed: { (_ , _ , _ , _ , _ ) -> Void in
                    //异步任务执行完毕之后 需要在任务池 －1
                    dispatch_group_leave(group)
                    print("完成单张图片的下载")
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //需要完成回调  统一的回调
            printLog("原创微博的单张图片下载完成")
            finished(isSuccess: true)
        }
    }

}
